package com.knife.news.action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.knife.member.Userinfo;
import com.knife.member.UserinfoDAO;
import com.knife.news.logic.NewsService;
import com.knife.news.logic.RelativeService;
import com.knife.news.logic.SiteService;
import com.knife.news.logic.TypeService;
import com.knife.news.logic.impl.CommentServiceImpl;
import com.knife.news.logic.impl.NewsServiceImpl;
import com.knife.news.logic.impl.RelativeServiceImpl;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.logic.impl.TypeServiceImpl;
import com.knife.news.object.Comment;
import com.knife.news.object.News;
import com.knife.news.object.Site;
import com.knife.news.object.Type;
import com.knife.news.stat.StatHandle;
import com.knife.util.CommUtil;
import com.knife.web.ActionContext;
import com.knife.web.Module;
import com.knife.web.WebForm;
import com.knife.web.tools.AbstractCmdAction;

abstract class BaseCmdAction extends AbstractCmdAction {
	public NewsService newsDAO = NewsServiceImpl.getInstance();
	public RelativeService relativeDAO = RelativeServiceImpl.getInstance();
	public TypeService typeDAO = TypeServiceImpl.getInstance();
	public SiteService siteDAO = SiteServiceImpl.getInstance();
	public CommentServiceImpl commentDAO = CommentServiceImpl.getInstance();
	public Site thisSite;
	public Type thisType;
	public News thisNews;
	public int count = 0;
	List<News> indexNews = new ArrayList<News>();
	public String sid = "";
	public String tid = "";
	private String id = "";
	public String treenews="";
	public String loginUser = null;
	public Userinfo onlineUser = null;

	public Object doBefore(WebForm form, Module module) {
		form.addResult("newsDAO", newsDAO);
		form.addResult("relativeDAO", relativeDAO);
		form.addResult("typeDAO", typeDAO);
		form.addResult("siteDAO", siteDAO);
		sid 	= CommUtil.null2String(form.get("sid"));
		tid 	= CommUtil.null2String(form.get("tid"));
		id 		= CommUtil.null2String(form.get("id"));
		treenews = CommUtil.null2String(form.get("treenews"));
		if("".equals(sid)){
			thisSite = siteDAO.getSite();
			sid = "0";
		}else{
			thisSite = siteDAO.getSiteById(sid);
		}
		if (tid.equals("")) {
			tid = "0";
		}
		if (id.equals("")) {
			id = "0";
		}
		if(treenews.equals("")){
			treenews="0";
		}
		if (!tid.equals("0")) {
			thisType = typeDAO.getTypeById(tid);
			if(thisType!=null){
			if(thisType.getSite()!=null){
				if(!"0".equals(thisType.getSite())){
					thisSite = siteDAO.getSiteById(thisType.getSite());
				}
			}
			}
			List<News> topnews = newsDAO.getTopNews(tid, 1);
			if (topnews != null) {
				if (topnews.size() > 0) {
					if(!treenews.equals("0")){
						if(newsDAO.getTopNews(tid,treenews, 1).size()>0){
							thisNews = (News) newsDAO.getTopNews(tid,treenews, 1).get(0);
						}
					}else{
						if(newsDAO.getTopNews(tid, 1).size()>0){
							thisNews = (News) newsDAO.getTopNews(tid, 1).get(0);
						}
					}
				}
			}
		}
		if (!id.equals("0")) {
			thisNews = newsDAO.getNewsById(id);
			if (thisNews != null) {
				if(tid.equals("0")){
					tid = CommUtil.null2String(thisNews.getType());
					if (tid.length() > 0) {
						thisType = typeDAO.getTypeById(tid);
						if(thisType!=null){
						if(thisType.getSite()!=null){
							if(!"0".equals(thisType.getSite())){
								thisSite = siteDAO.getSiteById(thisType.getSite());
							}
						}
						}
					}
				}
			}
		}
		if(thisSite != null){
			form.addResult("thisSite", thisSite);
			//form.addResult("template", "web/" + thisSite.getTemplate() + "/");
			//this.setTemplatePath(Globals.APP_BASE_DIR + "WEB-INF/templates/web/" + thisSite.getTemplate() + "/");
			List<Type> nav = typeDAO.getSubTypesById(thisSite.getId(),"0", 1);
			form.addResult("nav", nav);
			indexNews = newsDAO.getIndexNews(thisSite.getId());
			form.addResult("indexNews", indexNews);
		}
		if (thisType != null) {
			form.addResult("thisType", thisType);
		}
		if (thisNews != null) {
			form.addResult("thisNews", thisNews);
			Collection<Object> paras = new ArrayList<Object>();
			paras.add(thisNews.getId());
			List<Comment> comments=commentDAO.getCommBySql("id!='' and k_news_id=? and k_display=1", paras,0, -1);
			form.addResult("comments", comments);
		}
		// 获取访问数据
		HttpServletRequest request = ActionContext.getContext().getRequest();
		String url = getUrl(request);
		try {
			count = StatHandle.select(url);
		} catch (Exception ex) {
		}
		form.addResult("count", count);
		// 获取用户登陆情况
		//先判断cookie
		/*if (request.getCookies() != null) {
			Cookie[] allCookie = request.getCookies();
			for (int i = 0; i < allCookie.length; i++) {
				if (allCookie[i].getName().equals("loginuser")) {
					loginUser = allCookie[i].getValue();
					break;
				}
			}
		}
			List<String> loginUsers=SessionUtil.getUserList();
			boolean isonline=false;
			for(String auser : loginUsers){
				if(loginUser.equals(auser)){
					isonline=true;
					break;
				}
			}
			if(!isonline){loginUser=null;}
		*/
		//判断session
		HttpSession olSession=ActionContext.getContext().getSession();
		if(olSession!=null){
			if(olSession.getAttribute("loginuser")!=null){
				loginUser=olSession.getAttribute("loginuser").toString();
			}
		}
		if(loginUser!=null){
			UserinfoDAO udao=new UserinfoDAO();
			try{
				onlineUser=(Userinfo)udao.findActiveByAcount(loginUser).get(0);
				ServletContext ContextA = olSession.getServletContext(); 
				ContextA.setAttribute("loginuser", olSession);
			}catch(Exception e){
			}
			form.addResult("user", onlineUser);
		}
		form.addResult("loginUser", loginUser);
		return super.doBefore(form, module);
	}
	
	public Object doAfter(WebForm form, Module module) {
		countVisit();
		return super.doAfter(form, module);
	}

	private String getUrl(HttpServletRequest request) {
		String url = request.getScheme() + "://";
		url += request.getHeader("host");
		url += request.getRequestURI();
		if (request.getQueryString() != null){
			url += "?" + request.getQueryString();
		}
		return url;
	}

	private void countVisit() {
		HttpServletRequest httpRequest = (HttpServletRequest) ActionContext
				.getContext().getRequest();
		String ip = httpRequest.getRemoteAddr();
		if (ip == null) {
			ip = "未知";
			// 如果读取的IP为空，则赋值为“未知”
		}
		// 从请求头中取出客户端IP地址
		String agent = httpRequest.getHeader("User-Agent");
		System.out.println("HTTP-HEAD: " + agent);
		// 从请求头中读取User-Agent值
		StringTokenizer st = new StringTokenizer(agent, ";)");
		// 构造StringTokenizer对象，使用“；”“）”来分解User-Agent值
		String browser="未知";
		String os="未知";
		if(st.nextToken()!=null){
			try{
				browser = st.nextToken();
				os = st.nextToken();
			}catch(Exception e){
			}
		}
		String url = getUrl(httpRequest);
		if (browser == null) {
			browser = "未知";
			// 如果读取的浏览器名为空，则赋值为“未知”
		}
		if (os == null) {
			os = "未知";
			// 如果读取的操作系统名为空，则赋值为“未知”
		}
		try {
			StatHandle.insert(ip, os.trim(), browser.trim(), url.trim());
			// 调用业务逻辑，将用户数据插入到数据库中
		} catch (Exception es) {
			es.printStackTrace();
			// 在输入日志中打印异常信息
		}
	}
}